import { reactive, ref, toRaw, computed } from 'vue';
import { isArray, debounce, getSystemConfig, Modal } from '@jecloud/utils';
import { accountLoginApi, dynamicLoginApi, sendCaptchaApi } from '../api/login';
import { useI18n, login } from '@/service/helper';
import { accountLoginValidate, dynamicLoginValidate, phoneValidate } from './use-validate';
import { PAGE_LOGIN_PASSWORD_URL } from './constant';
import { useGlobalStore } from '@/service/store/global-store';
import LoginLogoUrl from '@/service/assets/images/login-logo.png';
export function useLogin() {
  const { t } = useI18n();
  const globalStore = useGlobalStore();
  const form = ref();
  const loading = ref(false);
  // 登录方式
  const loginType = ref(
    (getSystemConfig('JE_CORE_VERIFY') || 'ACCOUNT')
      .toLocaleLowerCase()
      .split(',')
      .map((type) => t(`login.placeholder.${type}`))
      .join('/'),
  );
  // 启用找回密码
  const enableFindPassword = getSystemConfig('JE_CORE_PHONEREPASSWORD') == '1';
  // 启用验证码登录
  const enableCaptchaLogin = getSystemConfig('JE_CORE_PHONELOGIN') == '1';

  // 动态密码登录
  const accountPassword = ref(true);
  // 表单数据
  const model = reactive({
    account: '', // 用户名
    password: '', // 密码
    phone: '', // 手机号
    captcha: '', // 验证码
    deptId: '', // 部门ID
    savePassword: false, // 记住密码
  });
  initLoginModel(model);

  // 登录图标
  const loginLogoUrl = computed(() => {
    return globalStore.activeApp?.loginLogo || LoginLogoUrl;
  });
  const loginLogoStyle = computed(() => {
    return globalStore.activeApp?.loginLogoStyle;
  });
  const imageError = ref(false);
  const onImageError = (error) => {
    console.error(error);
    imageError.value = true;
  };

  // 登录
  const onLoginClick = () => {
    if (accountPassword.value) {
      accountLogin({ model, loading });
    } else {
      dynamicLogin({ model, loading });
    }
  };
  // 验证码
  const onTimerClick = debounce(($timer) => {
    sendCaptcha({ model, $timer }).then((message) => {
      Modal.toast(message, 'success');
    });
  }, 200);
  // 记住密码
  const onSavePasswordClick = () => {
    model.savePassword = !model.savePassword;
  };
  // 动态登录
  const onDynamicPasswordClick = () => {
    accountPassword.value = !accountPassword.value;
  };
  // 忘记密码
  const onForgetPasswordClick = () => {
    uni.navigateTo({ url: PAGE_LOGIN_PASSWORD_URL });
  };

  return {
    form,
    model,
    accountPassword,
    loading,
    loginLogoUrl,
    loginLogoStyle,
    imageError,
    onImageError,
    onSavePasswordClick,
    onDynamicPasswordClick,
    onForgetPasswordClick,
    onTimerClick,
    onLoginClick,
    loginType,
    enableCaptchaLogin,
    enableFindPassword,
    ...useLoginTheme(),
  };
}
/**
 * 账号登录
 */
function accountLogin({ model, loading }) {
  doLogin({ model, type: 'account', loading });
}

/**
 * 动态登录
 */
function dynamicLogin({ model, loading }) {
  doLogin({ model, type: 'dynamic', loading });
}

/**
 * 发送验证码
 * @param {*} param0
 */
export function sendCaptcha({ model, $timer }) {
  const { t } = useI18n();
  return phoneValidate(model.phone)
    .then(() => sendCaptchaApi(model))
    .then(() => {
      $timer.start();
      return { message: t('login.message.sendCaptchaSuccess') };
    })
    .catch(({ message }) => {
      return { message, status: 'error' };
    });
}

/**
 * 登录
 * @param {*} param0
 * @returns
 */
function doLogin({ model, type, loading }) {
  let loginApi = accountLoginApi;
  let validate = accountLoginValidate;
  loading.value = true;
  switch (type) {
    case 'dynamic':
      loginApi = dynamicLoginApi;
      validate = dynamicLoginValidate;
      break;
  }
  // 校验成功，登录
  return validate({ model })
    .then(() => loginApi(toRaw(model)))
    .then((result) => {
      if (isArray(result)) {
        // 选择部门
        chooseDepartment({ depts: result })
          .then((dept) => {
            model.deptId = dept.id;
            // 重新登录
            doLogin({ model, type, loading });
          })
          .catch(() => {
            model.deptId = '';
          });
      } else {
        // 记住密码
        if (type === 'account') {
          savePassword(model);
        }
        // 登录成功
        login({ token: result, goHome: true });
      }
      loading.value = false;
    })
    .catch(({ message }) => {
      // 错误信息
      Modal.toast({ message, status: 'error' });
      loading.value = false;
    });
}

/**
 * 多部门选择
 * @param {*} param0
 * @returns
 */
function chooseDepartment({ depts }) {
  const { t } = useI18n();
  const title = t('login.message.chooseDepartment');
  return uni
    .showActionSheet({
      title,
      alertText: title,
      itemList: depts.map((dept) => dept.name),
    })
    .then(({ tapIndex }) => {
      const dept = depts[tapIndex];
      return dept;
    });
}
/**
 * 记住密码
 * @param {*} model
 */
function savePassword(model) {
  uni.setStorage({
    key: 'login-account',
    data: model.account,
  });
  uni.setStorage({
    key: 'login-save-password',
    data: model.savePassword,
  });
  if (model.savePassword) {
    uni.setStorage({
      key: 'login-password',
      data: model.password,
    });
  } else {
    uni.removeStorage({
      key: 'login-password',
    });
  }
}
/**
 * 初始化登录model
 * @param {*} model
 */
function initLoginModel(model) {
  const account = uni.getStorageSync('login-account');
  const savePassword = uni.getStorageSync('login-save-password');
  const password = uni.getStorageSync('login-password');
  Object.assign(model, {
    account,
    password,
    savePassword,
  });
}
/**
 * 登录页主题
 * @returns
 */
export function useLoginTheme() {
  const globalStore = useGlobalStore();
  // 登录页主题色
  const style = computed(() => {
    return (
      '--login-primary-color: ' +
      (globalStore.theme.loginPrimaryColor || globalStore.theme.primaryColor)
    );
  });
  return { style };
}
